package com.joolun.web.controller.scrm;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.joolun.common.core.domain.entity.SysDept;
import com.joolun.common.core.domain.entity.SysUser;
import com.joolun.common.utils.SecurityUtils;
import com.joolun.system.service.ISysDeptService;
import com.joolun.web.huantuo.MTCloud;
import jakarta.servlet.http.HttpServletResponse;
import lombok.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.joolun.common.annotation.Log;
import com.joolun.common.core.controller.BaseController;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.enums.BusinessType;
import com.joolun.weixin.entity.ZbRedEnvelopes;
import com.joolun.weixin.service.IZbRedEnvelopesService;
import com.joolun.common.utils.poi.ExcelUtil;
import com.joolun.common.core.page.TableDataInfo;

/**
 * 直播间红包Controller
 * 
 * @author joolun
 * @date 2025-06-05
 */
@RestController
@RequestMapping("/zb/envelopes")
public class ZbRedEnvelopesController extends BaseController
{
    @Autowired
    private IZbRedEnvelopesService zbRedEnvelopesService;
    @Autowired
    private ISysDeptService deptService;

    // 使用ObjectMapper库解析JSON字符串
    ObjectMapper mapper = new ObjectMapper();

    // 根据登录用户获取openID和openToken
    public MTCloud getOpenIDAndOpenToken(){
        // 获取当前登录的用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 获取当前登录用户的部门
        SysDept dept = user.getDept();
        // 获取父级部门id
        Long parentId = dept.getParentId();
        // 获取父级部门对象
        SysDept parentDept = deptService.selectDeptById(parentId);
        System.out.println("OpenIdHt---------------" + parentDept.getOpenIdHt());
        if((parentDept.getOpenIdHt() != null && parentDept.getOpenIdHt() != "") && (parentDept.getOpenTokenHt() != null && parentDept.getOpenTokenHt() != "")){
            // 根据用户所属公司获取公司的openID和openToken
            return new MTCloud(parentDept.getOpenIdHt(),parentDept.getOpenTokenHt());
        }
        MTCloud mtCloud = new MTCloud();
        return mtCloud;
    }


    /**
     * 查询直播间红包列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ZbRedEnvelopes zbRedEnvelopes)
    {
        startPage();
        List<ZbRedEnvelopes> list = zbRedEnvelopesService.selectZbRedEnvelopesList(zbRedEnvelopes);
        return getDataTable(list);
    }
    /**
     * 查询直播间已关联商品
     */
    @GetMapping("/getRoomShopping")
    public TableDataInfo getRoomShopping(String shopId)
    {
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            String htResult = mtCloud.courseGoods(shopId);
            // 将返回结果转换为map
            Map<String, Object> htMap = mapper.readValue(htResult, Map.class);
            List<Map<String, Object>> htList = (List<Map<String, Object>>) htMap.get("data");
            if (htList == null) {
                htList = Collections.emptyList();
            }
            return getDataTable(htList);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        List<ZbRedEnvelopes> list = zbRedEnvelopesService.selectZbRedEnvelopesList(zbRedEnvelopes);
        return getDataTable(Collections.emptyList());
    }
    /**
     * 导出直播间红包列表
     */
    @PreAuthorize("@ss.hasPermi('zb:envelopes:export')")
    @Log(title = "直播间红包", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZbRedEnvelopes zbRedEnvelopes)
    {
        List<ZbRedEnvelopes> list = zbRedEnvelopesService.selectZbRedEnvelopesList(zbRedEnvelopes);
        ExcelUtil<ZbRedEnvelopes> util = new ExcelUtil<ZbRedEnvelopes>(ZbRedEnvelopes.class);
        util.exportExcel(response, list, "直播间红包数据");
    }

    /**
     * 获取直播间红包详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(zbRedEnvelopesService.selectZbRedEnvelopesById(id));
    }

    /**
     * 新增直播间红包
     */
    @PreAuthorize("@ss.hasPermi('zb:envelopes:add')")
    @Log(title = "直播间红包", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZbRedEnvelopes zbRedEnvelopes)
    {
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            HashMap<Object,Object> options = new HashMap<Object,Object>();
            options.put("name", zbRedEnvelopes.getName());
            options.put("img", zbRedEnvelopes.getImg());
            options.put("price", zbRedEnvelopes.getPrice());
            options.put("originalPrice", zbRedEnvelopes.getOriginalPrice());
            options.put("tab", zbRedEnvelopes.getTab());
            options.put("pay", zbRedEnvelopes.getPay());
            options.put("url", zbRedEnvelopes.getUrl());
            options.put("qrcode", zbRedEnvelopes.getQrcode());
            options.put("link_text", zbRedEnvelopes.getLinkText());
            String htResult =  mtCloud.goodsAdd(0, options);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            String dataMap =  map.get("code").toString();
            if ("0".equals(dataMap)) {
                Long id =  Long.parseLong(map.get("data").toString());
                zbRedEnvelopes.setId(id);
                zbRedEnvelopes.setCreateBy(getUsername());
                // 同步后台添加商品
                return toAjax(zbRedEnvelopesService.insertZbRedEnvelopes(zbRedEnvelopes));
            } else {
                String msg = map.get("msg").toString();
                System.out.println("---------------------添加失败---------------" + htResult);
                return error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    /**
     * 修改直播间红包
     */
    @PreAuthorize("@ss.hasPermi('zb:envelopes:edit')")
    @Log(title = "直播间红包", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZbRedEnvelopes zbRedEnvelopes)
    {
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            HashMap<Object,Object> options = new HashMap<>();
            options.put("name", zbRedEnvelopes.getName());
            options.put("img", zbRedEnvelopes.getImg());
            options.put("price", zbRedEnvelopes.getPrice());
            options.put("originalPrice", zbRedEnvelopes.getOriginalPrice());
            options.put("tab", zbRedEnvelopes.getTab());
            options.put("pay", zbRedEnvelopes.getPay());
            options.put("url", zbRedEnvelopes.getUrl());
            options.put("qrcode", zbRedEnvelopes.getQrcode());
            options.put("link_text", zbRedEnvelopes.getLinkText());
            String htResult =  mtCloud.goodsEdit(zbRedEnvelopes.getId(), options);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            String dataMap =  map.get("code").toString();
            if ("0".equals(dataMap)) {
                zbRedEnvelopes.setCreateBy(getUsername());
                // 同步修改后台商品
                return toAjax(zbRedEnvelopesService.updateZbRedEnvelopes(zbRedEnvelopes));
            } else {
                String msg = map.get("msg").toString();
                System.out.println("---------------------修改失败---------------" + htResult);
                return error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    /**
     * 删除直播间红包
     */
    @PreAuthorize("@ss.hasPermi('zb:envelopes:remove')")
    @Log(title = "直播间红包", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            String htResult =  mtCloud.goodsDel(ids[0]);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            String dataMap =  map.get("code").toString();
            if ("0".equals(dataMap)) {
                // 同步删除后台商品
                return toAjax(zbRedEnvelopesService.deleteZbRedEnvelopesByIds(ids));
            } else {
                String msg = map.get("msg").toString();
                System.out.println("---------------------删除失败---------------" + htResult);
                return error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    /**
     * 关联直播间商品
     */
    @PostMapping("/concatShopping")
    public AjaxResult concatAddShopping(@RequestBody ConcatShoppingParam param)
    {
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            String htResult =  mtCloud.courseGoodsImport(param.getRoomId(), param.getIds());
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            String dataMap =  map.get("code").toString();
            if ("0".equals(dataMap)) {
                return toAjax(1);
            } else {
                String msg = map.get("msg").toString();
                System.out.println("---------------------关联商品失败---------------" + htResult);
                return error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }
    /**
     * 删除关联直播间商品
     */
    @PostMapping("/delConcatShopping")
    public AjaxResult delConcatShopping(@RequestBody Map<String, Object> params)
    {
        String courseId = (String) params.get("courseId");
        String roomId = (String) params.get("roomId");
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            String htResult =  mtCloud.courseGoodsDel(courseId, roomId);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            String dataMap =  map.get("code").toString();
            if ("0".equals(dataMap)) {
                return toAjax(1);
            } else {
                String msg = map.get("msg").toString();
                System.out.println("---------------------取消关联商品失败---------------" + htResult);
                return error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    /**
     * 查询直播间商品入口展示
     */
    @PostMapping("/shopEntry")
    public AjaxResult getRoomShopEntry(@RequestBody Map<String, Object> params)
    {
        String courseId = (String) params.get("shopId");
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            String[] options = {"store","goodsPrompt","goodsList"};
            String htResult =  mtCloud.getLifeConfig(courseId, options);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            Map<String, Object> dataMap = (Map<String, Object>) map.get("data");
            return success(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error();
    }

    /**
     * 修改直播间商品入口展示
     */
    @PostMapping("/upShopEntry")
    public AjaxResult updateRoomShopEntry(@RequestBody Map<String, Object> params)
    {
        String courseId = (String) params.get("shopId");
        String store = (String) params.get("store");
        String goodsPrompt = (String) params.get("goodsPrompt");
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            HashMap<Object, Object> options = new HashMap<>();
            HashMap<Object, Object> storeMap = new HashMap<>();
            storeMap.put("enable", store);
            options.put("store", storeMap);
            HashMap<Object, Object> goodsPromptMap = new HashMap<>();
            goodsPromptMap.put("enable", goodsPrompt);
            options.put("goodsPrompt", goodsPromptMap);
            String htResult =  mtCloud.updateLifeConfig(courseId, options);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            String dataMap =  map.get("code").toString();
            if ("0".equals(dataMap)) {
                return toAjax(1);
            } else {
                String msg = map.get("msg").toString();
                System.out.println("---------------------修改直播间商品入口展示失败---------------" + htResult);
                return error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }


    @Data
    public static class ConcatShoppingParam {
        private Long[] ids;
        private String roomId;
    }
}
